/**
 * 
 */
package com.google.code.cisx.client.gadgets;

import com.google.code.cisx.client.dto.ProjectViewHelper;
import com.google.code.cisx.client.dto.QueryViewHelper;
import com.google.code.cisx.client.event.EventManager;
import com.google.code.cisx.client.gadgets.GadgetEvent.GadgetEventType;
import com.google.code.cisx.client.model.Gadget;
import com.google.code.cisx.client.model.GadgetClass;
import com.google.code.cisx.client.service.RemoteProjectService;
import com.google.code.cisx.client.service.RemoteServiceException;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

import java.util.List;

/**
 * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
 * @since 1.0
 * @version $Id: ProjectListGadget.java 153 2008-01-28 04:57:39Z
 *          rahul.thakur.xdev $
 */
public class ProjectListGadget extends Gadget implements GadgetEventListener<GadgetEvent> {

  public static class Class extends GadgetClass {
    public Class() {
      super("ProjectList", true, true /* secured */);
    }

    public Gadget newGadget() {
      return new ProjectListGadget(this);
    }

  }

  private FlexTable rows = new FlexTable();
  private String[] header = {"Name", "Group Id", "ArtifactId", "Version"};

  /**
   * @param gc
   */
  protected ProjectListGadget(GadgetClass gc) {
    super(gc);
    VerticalPanel mainPanel = new VerticalPanel();
    initWidget(mainPanel);
    mainPanel.setWidth("100%");
    rows.setWidth("100%");
    mainPanel.add(rows);
    rows.getRowFormatter().setStyleName(0, "gwtapps-ListHeaderRow");

    for (int i = 0; i < header.length; i++) {
      rows.setText(0, i, header[i]);
      rows.getCellFormatter().setStyleName(0, i, "List-ColumnLabel");
    }

    EventManager.getInstance().addEventListener(GadgetEventType.GADGET_INITIALIZED.toString(), this);
  }

  protected void addColumn(String name) {
    int column = rows.getRowCount() > 0 ? rows.getCellCount(0) : 0;
    rows.setWidget(0, column, new Label(name));
  }

  protected void addField(int row, String value) {
    row = row + 1;
    int column = 0;
    if (rows.getRowCount() == row) {
      if (row % 2 == 0)
        rows.getRowFormatter().setStyleName(row, "Even");
    } else {
      column = rows.getCellCount(row);
    }
    Label fieldValue = new Label(value);
    fieldValue.setStyleName("gwtapps-FieldValue");
    rows.setWidget(row, column, fieldValue);
  }

  public void onEvent(GadgetEvent event) {
    Gadget gadget = (Gadget) event.getSource();
    GWT.log("Handling GadgetEvent inside ProjectListGadget.", null);
    if (event.getType().equals(GadgetEventType.GADGET_INITIALIZED.toString())
        && (gadget instanceof ProjectListGadget)) {
      GWT.log("Handling GadgetEvent for ProjectListGadget.", null);
      try {
        final QueryViewHelper<ProjectViewHelper> query = new QueryViewHelper<ProjectViewHelper>();
        RemoteProjectService.Util.getAsyncInstance().query(query, 1, 5,
            new AsyncCallback<List<ProjectViewHelper>>() {
              public void onFailure(Throwable caught) {
                Window.alert("System error! Unable to fetch Project list.");
                rows.setWidget(1, 0, new HTML(
                    "<span style='color: red;'>System error! Unable to fetch Project list.</span>"));
              }

              public void onSuccess(List<ProjectViewHelper> result) {
                if (null != result) {
                  if (false)
                    rows.setText(1, 0, "Obtained " + result.size() + " projects." + result.get(0));
                  else {
                    int rowIdx = 1;
                    for (ProjectViewHelper p : result) {
                      rows.setText(rowIdx, 0, p.getName());
                      rows.setText(rowIdx, 1, p.getGroupId());
                      rows.setText(rowIdx, 2, p.getArtifactId());
                      rows.setText(rowIdx, 3, p.getVersion());
                      rowIdx++;
                    }
                  }
                } else
                  rows.setWidget(
                      1,
                      0,
                      new HTML(
                          "<span style='color: red;'>System error! Encountered NULL Project list.</span>"));
              }
            });
      } catch (RemoteServiceException e) {
        Window.alert("Exception encountered! Unable to fetch projects.");
        rows.setWidget(1, 0, new HTML(
            "<span style='color: red;'>System error! Unable to fetch Project list.</span>"));
      }
    } else {
      GWT.log("Unhandled GadgetEvent: " + event.getType() + ", source: "
          + gadget.getClass().getName(), null);
    }
  }
}
